package com.tianmao.swing.core;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;

public class PrintPaper {

    // 加载 DLL 库文件
    static {
        System.loadLibrary("TSCLIB");
        // 解决中文乱码
        System.setProperty("jna.encoding", "GBK");
    }


    public void receiveJson(String jsonData) {
        if (jsonData == null || jsonData.trim().isEmpty()) {
            System.err.println("JSON 数据为空，无法执行打印任务！");
            return;
        }
        JSONObject obj = JSONObject.parseObject(jsonData);
//        System.out.println(obj.toJSONString());
        int labelWidth = obj.getIntValue("width");
        int labelHeight = obj.getIntValue("height");
        int printreverse = obj.getIntValue("printreverse");
        System.out.println("打印方向：" + printreverse);
        System.out.println("解析后的 JSON 数据: " + obj.toJSONString());
        System.out.println("标签宽度: " + labelWidth + ", 标签高度: " + labelHeight);

        JSONArray labels = obj.getJSONArray("data");
        for (int i = 0; i < labels.size(); i++) {
            JSONObject label = labels.getJSONObject(i);
            printLabel(label,labelWidth,labelHeight,i,printreverse);
        }
    }

    private void printLabel(JSONObject label, int labelWidth, int labelHeight, int index, int printreverse) {
        String printName = "";
        // 获取默认打印服务
        PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
        if (defaultPrintService != null) {
            // 若找到默认打印机，打印其名称
            printName = defaultPrintService.getName();
        } else {
            System.out.println("未找到默认打印机。");
            printName = "Urovo D7120";
        }
        JniDll.TscLibDll.INSTANCE.openport(printName);
        //设置打印机方向
        if (printreverse == 1){
            JniDll.TscLibDll.INSTANCE.sendcommand("DIRECTION 1");
            System.out.println("正向打印");
        }else if(printreverse == 2){
            JniDll.TscLibDll.INSTANCE.sendcommand("DIRECTION 0");
            System.out.println("反向打印");
        }
        try {
            System.out.println("设置标签参数：宽度=" + labelWidth + "，高度=" + labelHeight);
            JniDll.TscLibDll.INSTANCE.setup(String.valueOf(labelWidth), String.valueOf(labelHeight), "5", "8", "0", "3", "0");

            JniDll.TscLibDll.INSTANCE.clearbuffer();

            JSONArray content = label.getJSONArray("content");
            for (int i = 0; i < content.size(); i++) {
                JSONObject item = content.getJSONObject(i);

                // 检查 x 和 y 是否存在
                if (!item.containsKey("xmm") || !item.containsKey("ymm")) {
                    continue;
                }

                double xmm = item.getDoubleValue("xmm");
                double ymm = item.getDoubleValue("ymm");
                // 打印文本内容
                if (item.containsKey("lable") && !item.getString("lable").startsWith("barlable:")
                        && !item.getString("lable").startsWith("QRlable:") && !(item.containsKey("type") && item.getString("type").endsWith("code"))) {
                    String lable = item.getString("lable");
                    String font = "宋体"; // 默认字体
                    if (item.containsKey("fontstylevalue")) {
                        font = item.getString("fontstylevalue");
                    }
                    System.out.println("字体" + font);
                    int fontsize = 16 * 2; // 默认字体大小
                    if (item.containsKey("fontsizevalue")) {
                        fontsize = item.getIntValue("fontsizevalue") * 2;
                    }
                    System.out.println("字体大小" + fontsize);
                    int fontweightvalue = 0;//默认字体粗细
                    if (item.containsKey("fontweightvalue")) {
                        int temp = item.getIntValue("fontweightvalue");
                        if(temp > 400){
                            fontweightvalue = 2;
                        }
                    }
                    int lineLength = 11;
                    String indent = "         "; // 定义要添加的空格，可按需调整
                    int endIndex = 17;
                    if(lable.startsWith("资产名称") && lable.length() > endIndex){
                        for (int j = 0; j < lable.length(); j += lineLength) {
                            String line = "";
                            if(j == 0){
                                line = lable.substring(j, endIndex-1);
                                endIndex = endIndex-1;
                            }else{
                                int start = endIndex;
                                endIndex = Math.min(endIndex+lineLength, lable.length());
                                line = lable.substring(start, endIndex);
                                if(line.equals("")){
                                    continue;
                                }
                            }
                            if (j > 0) {
                                line = indent + line;
                            }
                            System.out.println(lable+line);
                            if(line.length() > 9){
                                JniDll.TscLibDll.INSTANCE.windowsfont((int) (xmm * 8), (int) (ymm * 8) +10+ (j / lineLength) * fontsize, fontsize, 0, fontweightvalue, 0, font, line);
                            }
                        }
                    }else{
                        JniDll.TscLibDll.INSTANCE.windowsfont((int) (xmm * 8), (int) (ymm * 8), fontsize, 0, fontweightvalue, 0, font, lable);
                    }
                }

                // 动态提取一维码内容
                if (item.containsKey("type") && item.getString("type").equals("barcode")) {
                    // 打印条码
                    String barcodeContent = item.getString("barcodelable_" + index); // 获取条码内容
                    int x = (int) (xmm * 8);
                    int y = (int) (ymm * 8);
                    System.out.println("条码内容: " + barcodeContent);
                    int fontsize = 30; // 默认字体大小
                    if (item.containsKey("fontsizevalue")) {
                        fontsize = item.getIntValue("fontsizevalue") * 2;
                    }
                    JniDll.TscLibDll.INSTANCE.barcode(String.valueOf(x), String.valueOf(y), "128", "30", "0", "0", "2", "2", barcodeContent);
                    //不用这个了，分开了，目前只是纸质的分开
                    //JniDll.TscLibDll.INSTANCE.windowsfont(x + 15, y + 32, fontsize, 0, 4, 0, "宋体", barcodeContent);
                }
                //新的编码，和条码码分开了，目前只有纸质的分开了
                if(item.containsKey("type") && item.getString("type").equals("codeval")){
                    String qrCodeContent = item.getString("codeval_" + index); // 获取编码
                    String font = "宋体"; // 默认字体
                    if (item.containsKey("fontstylevalue")) {
                        font = item.getString("fontstylevalue");
                    }
                    System.out.println("字体" + font);
                    int fontsize = 16 * 2; // 默认字体大小
                    if (item.containsKey("fontsizevalue")) {
                        fontsize = item.getIntValue("fontsizevalue") * 2;
                    }
                    System.out.println("字体大小" + fontsize);
                    int fontweightvalue = 0;//默认字体粗细
                    if (item.containsKey("fontweightvalue")) {
                        int temp = item.getIntValue("fontweightvalue");
                        if(temp > 400){
                            fontweightvalue = 2;
                        }
                    }
                    JniDll.TscLibDll.INSTANCE.windowsfont((int) (xmm * 8), (int) (ymm * 8)-10, fontsize, 0, fontweightvalue, 0, "宋体", qrCodeContent);
                }

                // 动态提取二维码内容
                if (item.containsKey("type") && item.getString("type").equals("QRcode")) {
                    // 打印二维码
                    String qrCodeContent = item.getString("QRcodelable_" + index); // 获取二维码内容
                    int QRcodesizevalue = 4;
                    int yy = 90;
                    if (item.containsKey("QRcodesizevalue")) {
                        yy = (int)(item.getIntValue("QRcodesizevalue") * 1.7);
                        QRcodesizevalue = item.getIntValue("QRcodesizevalue")/10-1;
                    }
                    int x = (int) (xmm * 8);
                    int y = (int) (ymm * 8);
                    System.out.println("二维码内容: " + qrCodeContent);
                    JniDll.TscLibDll.INSTANCE.sendcommand("QRCODE " + x + "," + y + ",L,"+QRcodesizevalue+",A,0,M2,S1,\"" + qrCodeContent + "\"");
                    //资产编码在下方
                    //JniDll.TscLibDll.INSTANCE.windowsfont(x+5, y + yy, 20, 0, 4, 0, "宋体", qrCodeContent);
                }
            }

            JniDll.TscLibDll.INSTANCE.printlabel("1", "1");
            JniDll.TscLibDll.INSTANCE.clearbuffer();
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            JniDll.TscLibDll.INSTANCE.closeport();
        }
    }
}